package com.fengxu.gamescript.ui.signin

import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.webkit.JavascriptInterface
import android.webkit.WebView
import android.widget.TextView
import com.fengxu.gamescript.R
import com.fengxu.gamescript.data.GlobalData
import com.fengxu.gamescript.provide.ProviderFactory
import com.fengxu.gamescript.ui.base.BaseActivity
import com.fengxu.gamescript.util.CommonUtils
import com.xuexiang.xui.widget.toast.XToast
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.sdk27.coroutines.onClick

class SignInActivity : BaseActivity() {

    val webView:WebView by lazy {
        findViewById(R.id.signin_webview)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_sign_in)
        initView()
    }

    @SuppressLint("JavascriptInterface")
    private fun initView() {
        findViewById<View>(R.id.actionbar_back).onClick { finish() }
        findViewById<TextView>(R.id.actionbar_title).text = "今日签到"
        webView.settings.domStorageEnabled = true
        webView.settings.javaScriptEnabled = true
        webView.loadUrl("file:///android_asset/signIn/index.html")
        webView.addJavascriptInterface(this, "Android")
    }

    /**
     * 签到获取次数
     */
    @JavascriptInterface
    fun signIn(){
        val loadingDialog = CommonUtils.loadingDialog(this)
        doAsync {
            val result = ProviderFactory.dataProvider.userSignIn()
            if(result == null){
                XToast.error(this@SignInActivity,"网络连接失败!").show()
                loadingDialog.dismiss()
            }
            if(result.code == 200){
                // 签到成功
                runOnUiThread {
                    webView.loadUrl("javascript:window.start(${result.data})")
                }
            }else{
                // 签到失败，已经签到了
                runOnUiThread { XToast.error(this@SignInActivity, result.msg).show() }
            }
            runOnUiThread {
                loadingDialog.dismiss()
                if(result.remainTimes != null){
                    GlobalData.user!!.remainTimes = result.remainTimes
                }
            }
        }
    }

    /**
     * 抽奖动画完成
     */
    @JavascriptInterface
    fun animEnd(){
        XToast.success(this, "抽奖完成,即将回到主界面!").show()
        uiHandler.postDelayed({
            finish()
        },1000)
    }
}